let page = 2;
let limit = 20;
//点击查看更多聊条记录
function findchatmsg() {
	//聊天记录
	findchats({
		roomID: $(".username").attr("data-id"),
		username: $("#name").attr("data-username"),
		page: page,
		limit: limit
	});
	page += 1;

};

//发送购买单
function buy_Order(e) {
	let roomid = $(".username").attr("data-id");
	let msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	layer.confirm('是否要生成购买单并发送给用户？', {
		btn: ['确定', '取消'], //按钮
		success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
		}
	}, function() {
		let span = $("div[roomid='" + roomid + "'] .Scroll_area>span>b");
		var suggestdrugs = [];
		if(span.length > 0) {
			//保存购买单	
			let username = $("div[roomid='" + roomid + "'] .username_S_left").text();
			let data = $("div[roomid='" + roomid + "'] .userdate_S_left").text();
			let height = $("div[roomid='" + roomid + "'] .height_S_left").text();
			let weight = $("div[roomid='" + roomid + "'] .weight_S_left").text();
			let gender_s = $("div[roomid='" + roomid + "'] .all_men").html() || $("div[roomid='" + roomid + "'] .wormen").html();
			let medical = $("div[roomid='" + roomid + "'] .input_medical_left").text();
			let allergy = $("div[roomid='" + roomid + "'] .input_allergy_left").text();

			let userid = $('.yaoqing option:selected').attr("data-userid");
			let userrole = $('.yaoqing option:selected').attr("data-userrole");
			//客服汇总
			let servicetext = $("div[roomid='" + roomid + "'] .service_of_").val();
			if(!username || !data || !height || !weight) {
				layer.msg('请完善基本信息!', {
					icon: 2
				});
				return;
			};
			let datapars = {
				_id: $("div[roomid='" + roomid + "']").attr("_id"),
				roomid: $(".closes").attr("data-id"), //用户id 商城登陆用户id 小程序openid
				name: username, //姓名
				birthday: data, //出生日期
				gender: (gender_s == "男" ? 1 : 0), //性别
				height: height, //身高
				weight: weight, //体重
				medicalHistory: medical, //病史
				allergy: allergy, //过敏史
				serverSuggest: servicetext,
				serverName: $("#name").attr("data-name")
			};
			if(!(datapars._id)) {
				layer.msg('请完善收集单！', {
					icon: 2
				});
				return;
			};
			let span = $("div[roomid='" + roomid + "'] .Scroll_area>span>b");
			let druglistings = ``;
			var suggestdrugs = [];
			if(span.length > 0) {
				for(var i = 0; i < span.length; i++) {
					druglistings += `<p><span>${$(span[i]).text()}</span> <span>X <b>${$(span[i]).next('input').val()}</b></span></p>`;
					suggestdrugs[i] = {
						productid: $(span[i]).attr('pid'),
						productname: $(span[i]).text(),
						isdrugstatus: $(span[i]).attr('isdrugstatus'),
						img: $(span[i]).attr('img'),
						marketprice: $(span[i]).attr('marketprice'),
						costprice: $(span[i]).attr('costprice'),
						count: $(span[i]).next('input').val(),
					};
				};
				datapars.serMedicinal = JSON.stringify(suggestdrugs) //选择的药品
			} else {
				datapars.serMedicinal = JSON.stringify([]); //药品为空
			};
			if(userrole == 1) {
				datapars.receiveId = userid;
			} else if(userrole == 6) {
				datapars.receiveId = userid;
			};
			$.ajax({
				url: serverURL + 'serdiagnosis',
				type: 'post',
				data: datapars,
				headers: {
					'Authorization': 'Bearer ' + msg.token
				},
				success: function(d) {
					console.log(d);
					if(d.code == 200) {
						layer.msg('已发送购买单！', {
							icon: 1
						});
						let buySingleinfos = `	
						<span>姓名：<b class="uname">${username}</b></span>
						<span>生日：<b class="uage">${data}</b></span>
						<span>性别：<b class="usex">${gender_s}</b></span>
						<span>身高：<b class="uheight">${height}</b></span>
						<span>体重：<b class="uweight">${weight}</b></span>
						<p class="paddingp">即往病史：<b class="udochis">${medical}</b></p>
						<p class="paddingp">过敏史：<b class="umedicine">${allergy}</b></p>`;
						$(".druglisting").html(druglistings);
						$(".buySingleinfo").html(buySingleinfos);
						$(".buySingledate").html(moment().format('YYYY年MM月DD日'));
						$(".zzzzc").show(); //显示购买单	
						socket.emit("message", {
							msg: "已发送购买单",
							roomID: $(".username").attr("data-id"),
							username: $("#name").attr("data-username"),
							userRole:$("#name").attr("userrole"),
							type: 'msg',
							b: 1,
							anonymityImg: "https://xcximg.juseyun.com/Images/servers.png",
							color: false,
							headerimg: null,
							to: d._id,
							imggs: "",
							id: 0,
							is: $("#name").attr("data-username"),
						});
						//发送购买单数据
						socket.emit("private_data", {
							dataType: 1,
							roomID: $(".username").attr("data-id"),
							buySingle: datapars,
							_id: d._id
						});
						let html = `<li class="layim-chat-mine">
				    	<div class="layim-chat-user">
						<img src="https://xcximg.juseyun.com/Images/servers.png">
							<cite><i>${$("#name").attr("data-username")}</i>${moment().format('hh:mm:ss')}</cite>
							</div>
							<div class="layim-chat-text" style="color:white;background-color=;background-color:#1abb9c;">已发送购买单</div>
						</li>`
						$('.layim-chat-main>ul').append(html);
						$('.chat-thread').append('<div class="layim-chat-system"><span layim-event="chatLog"><a id="' + d._id + '" onclick="findinfo_Order(event)">查看购买单</a></span></div>');
					} else {
						if(d.text){
						 layer.msg(d.text, {
								icon: 2
							});
						}else{
							layer.msg("购买单已生成！", {
								icon: 2
							});
						}
					};
				},
				error: function(err) {
					layer.msg('已发送购买单失败,请重新生成购买单！', {
						icon: 2
					});
				}
			});
		} else {
			layer.msg('您还没有选择药品,请选择药品!', {
				icon: 2
			});
		};
	}, function() {
		layer.msg('取消发送购买单！', {
			icon: 2
		});
	});
};

//首页修改密码
function change_Passwords() {
	$(".layui-layer-shade,.layui-layer-page,.layui-layer-btn1").show();
};
//确认
function change_Password(){
	let msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	if(!$('.newpwd').val() || !$('.repeatpwd').val()) {
		$(".login_failed").html("输入的密码不能为空！");
		return;
	};
	if($('.newpwd').val() != $('.repeatpwd').val()) {
		$(".login_failed").html("两次输入的密码不相同！");
	} else if($('.repeatpwd').val().length<6||$('.newpwd').val().length<6) {
		$(".login_failed").html("密码长度不能小于6位数！");
	}else{
		$.ajax({
			url: urls + '/regist/changePassWord',
			type: 'post',
			data: {
				userPassword: $('.oldpwd').val(),
				newUserPassword: $('.newpwd').val()
			},
			headers: {
				'Authorization': 'Bearer ' + msg.token
			},
			success: function(d) {
				if(parseInt(d) == 200) {
					window.sessionStorage.setItem("changetime", true);
					$(".layui-layer-shade,.layui-layer-page").hide();
					layer.open({
						title: '系统提示',
						content: '修改密码成功',
						success: function(layero) {
							 layero.find(".layui-layer-btn0").css({
							 	"border-color":"#1abb9c",
							 	"background-color":"#1abb9c"
							 })	
						}
					});
					window.location = "../pages_doctor/html/login.html";
					$('.newpwd').val("");
					$('.repeatpwd').val("");
					$('.oldpwd').val("");
				} else if(parseInt(d) == 201) {
					$(".login_failed").html("原始密码或新密码不能为空！");
				} else if(parseInt(d) == 202) {
					$(".login_failed").html("原始密码错误！");
				} else {
					$(".login_failed").html("发生意外错误，刷新后重试！");
				}
			}
		});
	}
};
//取消
$(".layui-layer-btn1").on("click", function() {
	$(".layui-layer-shade,.layui-layer-page").hide();
});
//发送药品信息
function sendToAssDoc() {
	let roomid = $(".username").attr("data-id");
	if(!($("div[roomid='" + roomid + "'] .infoname").val()) || !($("div[roomid='" + roomid + "'] .username_S_left").text())) {
		$('.assign_a_doctor_show').css({
			'display': 'none'
		})
	};
	//判断数据是否满足要求
	$('.assign_a_doctor_show').css({
		'display': 'none'
	})
	let username = $("div[roomid='" + roomid + "'] .username_S_left").text();
	let data = $("div[roomid='" + roomid + "'] .userdate_S_left").text();
	let height = $("div[roomid='" + roomid + "'] .height_S_left").text();
	let weight = $("div[roomid='" + roomid + "'] .weight_S_left").text();
	let medical = $("div[roomid='" + roomid + "'] .input_medical_left").text();
	let allergy = $("div[roomid='" + roomid + "'] .input_allergy_left").text();
	let gender_s = $("div[roomid='" + roomid + "'] .all_men").html() || $(".apendhtml[roomid='" + roomid + "'].wormen").html();
	let answer = [];
	let socketid = $('.yaoqing option:selected').attr("data-id");
	let doctorname = $('.yaoqing option:selected').html();
	let userid = $('.yaoqing option:selected').attr("data-userid");
	let userrole = $('.yaoqing option:selected').attr("data-userrole");
	//	if(!$("div[roomid='" + roomid + "']").attr("uderinfo_id")) {
	//		layer.open({
	//			title: '系统提示',
	//			content: '请将用户基本信息单发至用户填写！',
	//		});
	//		return;
	//	};
	//系统诊断
	let systenm = $("div[roomid='" + roomid + "'] .System_in_the_diagnosis_of").text();
	//客服汇总
	let servicetext = $("div[roomid='" + roomid + "'] .service_of_").val();

	//建议用药
	//let suggestdrug=[];
	let datapars = {
		userid: $(".closes").attr("data-id"), //用户id 商城登陆用户id 小程序openid
		mesId: $("div[roomid='" + roomid + "']").attr("uderinfo_id"),
		name: username, //姓名
		birthday: data, //出生日期
		gender: (gender_s == "男" ? "1":"0"), //性别
		height: height, //身高
		weight: weight, //体重
		medicalHistory: medical, //病史
		allergy: allergy, //过敏史
		information: JSON.stringify(subject[_privateSingles][0]),
		informations: JSON.stringify(subject[_privateSingles]),
		serverSuggest: servicetext,
		serverId: $("#name").attr("data-name"),
		serverName: $("#name").attr("data-name"),
		userPhone: $(".closes").attr("userphone")
	};
	if(userrole == 1) {
		datapars.receiveId = userid;
	} else if(userrole == 6) {
		datapars.receiveId = userid;
	};
	let span = $("div[roomid='" + roomid + "'] .Scroll_area>span>b");
	var suggestdrugs = [];
	if(span.length > 0) {
		for(var i = 0; i < span.length; i++) {
			suggestdrugs[i] = {
				productid: $(span[i]).attr('pid'),
				productname: $(span[i]).text(),
				isdrugstatus: $(span[i]).attr('isdrugstatus'),
				img: $(span[i]).attr('img'),
				marketprice: $(span[i]).attr('marketprice'),
				costprice: $(span[i]).attr('costprice'),
				count: $(span[i]).next('input').val(),
			};
		};
		datapars.serMedicinal = JSON.stringify(suggestdrugs) //选择的药品
	} else {
		datapars.serMedicinal = JSON.stringify([]); //药品为空
	};
	let msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	$.ajax({
		url: serverURL + "saveUserMes",
		traditional: true,
		type: "post",
		dataType: "json",
		data: datapars,
		async: true,
		headers: {
			'Authorization': 'Bearer ' + msg.token
		},
		success: function(res) {
			console.log(res);
			if(res.code == 200) {
				if(res._id) {
					$("div[roomid='" + roomid + "'] .System_in_the_diagnosis_of").text(res.systemResult.join(""));
				};
				layer.open({
					title: '系统提示',
					content: '保存成功',
					success: function(layero) {
						 layero.find(".layui-layer-btn0").css({
						 	"border-color":"#1abb9c",
						 	"background-color":"#1abb9c"
						 })	
				    }
				});
				$("div[roomid='" + roomid + "']").attr("_id", res._id);
			}
		},
		error: function(err) {
			console.log(err)
		}
	})
};
//重置药品搜索条件
$(".reset").on("click", function() {
	$(".p_name").val("");
	$('.pageindex_p').val(1);
	if($("#category option[value='']").attr("selected") == "selected") {
		$("#category option[value='']").removeAttr("selected");
		$("#category option[value='']").attr("selected", "selected");
		$("#p_store option[value='']").removeAttr("selected");
		$("#p_store option[value='']").attr("selected", "selected");
	} else {
		$("#category option[value='']").attr("selected", "selected");
		$("#p_store  option[value='']").attr("selected", "selected");
	};
});
//购买单查看
function findinfo_Order(e) {
	console.log(e.target.id);
	var msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	let roomid = $(".username").attr("data-id");
	$.ajax({
		type: "post",
		url: serverURL + "mes",
		async: true,
		data: {
			_id: e.target.id
		},
		headers: {
			'Authorization': 'Bearer ' + msg.token
		},
		success: function(res) {
			console.log(res);
			if(res.code == 200) {
				if(res.data) {
					let druglistings = ``;
					if(res.data.serMedicinal.OTC.length > 0) {
						for(var i = 0; i < res.data.serMedicinal.OTC.length; i++) {
							druglistings += `<p><span><a href="http://47.97.17.157:3000/html/Details.html?productId=${res.data.serMedicinal.OTC[i].productid}" title=" ${res.data.serMedicinal.OTC[i].productname}" target="_blank">${res.data.serMedicinal.OTC[i].productname}</a></span> <span>X <b>${res.data.serMedicinal.OTC[i].count}</b></span></p>`;
						};
					};
					let buySingleinfos = `	
						<span>姓名：<b class="uname">${res.data.name}</b></span>
						<span>生日：<b class="uage">${res.data.birthday}</b></span>
						<span>性别：<b class="usex">${res.data.gender==true?"男":"女"}</b></span>
						<span>身高：<b class="uheight">${res.data.height}</b></span>
						<span>体重：<b class="uweight">${res.data.weight}</b></span>
						<p class="paddingp">即往病史：<b class="udochis">${res.data.medicalHistory}</b></p>
						<p class="paddingp">过敏史：<b class="umedicine">${res.data.allergy}</b></p>`;
					$(".druglisting").html(druglistings);
					$(".buySingleinfo").html(buySingleinfos);
					$(".buySingledate").html(res.data.formTime);
					$(".zzzzc").show(); //显示购买单	
				}
			}
		},
		error: function(err) {
			layer.msg('查看购买单错误!请重试！', {
				icon: 2
			});
		}
	});
};

//查看电子诊断单
function Diagnosis_Order(e){
	     layer.open({
			  type: 2,
			  title: '电子问诊单详情',
			  shadeClose: true,
			  shade: 0.8,
			  area: ['90%', '90%'],
			  content: `../postpaper/postpaper.html?id=${e.target.id}&&name=3` //iframe的url
			});
}

//撤回指派
function Undo(e) {
	var msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	let roomid = $(".username").attr("data-id");
	let receiveId=$("div[roomid='" + roomid + "']").attr("receiveId");
	let soketid=get_SokcetId(receiveId,socketList);
	$.ajax({
		type: "get",
		url: serverURL + "back",
		async: true,
		data: {
			_id: $("div[roomid='" + roomid + "']").attr("_id")
		},
		headers: {
			'Authorization': 'Bearer ' + msg.token
		},
		success: function(res) {
			console.log(res);
			if(res.code == 200) {
				//撤回指派通知医生助理药师
				socket.emit("private_data", {
					dataType: 3,
					roomID: roomid,
					socket_id:soketid,
					_id: res._id,
					text: "撤回指派"
				});
				$(".Assigned_tothe_doctor").text("指派医生");
				layer.msg(res.mes, {
					icon: 1
				});
				//更改状态
				$.ajax({
					type: "post",
					url: serviceURL + "modification",
					async: true,
					data: {
						roomname:roomid,
						state:"指派医生"
					},
					headers: {
						'Authorization': 'Bearer ' + msg.token
					},
					success: function(res) {
						console.log(res);

					},
					error: function(err) {
						layer.msg('发生错误,请重试！', {
							icon: 2
						});
					}
				});
			} else {
				layer.msg(res.mes, {
					icon: 2
				});
			}

		},
		error: function(err) {
			layer.msg('发生错误,请重试！', {
				icon: 2
			});
		}
	});
};

//撤回邀请
function UndoInvite(e) {
	let roomid = $(".username").attr("data-id");
	console.log(e);
};

//获取socketid
function get_SokcetId(userid,socketlist){
	let socketid;
	 for (let a=0;a<socketlist.length;a++) {
	 	  if(socketlist[a].userid==userid){
	 	  	socketid=socketlist[a].id
	 	  }
	 }
	 return socketid;
}

//Enter修改密码
function onKeyPresss(event) {
	console.log(event)
	event = event || window.event;
	if(event.keyCode == 13) {
		change_Password();
	}
}